package cn.xiaolang.function.network.communicate;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class TcpClient {

    public static void main(String[] args) throws UnknownHostException, IOException {
        //创建一个客户端,并指定服务端的ip和端口号
        Socket client = new Socket("127.0.0.1", 10010);


        //创建一个字符输入流缓冲区对象，用转换流把键盘接收到的字节流转换为字符流
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        //从键盘录入一行数据
        System.out.print("please write a row data: ");
        String line;
        while ((line = br.readLine()) != null) {
            //获取客户端的字节输出流对象，用来向服务端传输数据
            OutputStream out = client.getOutputStream();
//	    	out.write(line.getBytes());//向服务端传送，从键盘接收的数据


            //创建一个打印流对象，把客户端要发送给服务端的数据封装起来，向服务端传输，并开启打印流的自动刷新功能
            PrintWriter pw = new PrintWriter(out, true);
            pw.println(line);//借用打印流对象，向服务端发送数据
            //获取客户端的字节输入流对象，接收从服务端返回的数据
            InputStream input = client.getInputStream();
            if (input == null) {
                System.out.println("write content shouldn't null");
                break;
            }
            byte[] buf = new byte[1024];
            int len = input.read(buf);
            System.out.println("[server] " + client.getInetAddress().getHostName() + " return data: " + new String(buf, 0, len));
            System.out.print("\nplease write a row data: ");
        }
        client.close();
    }


}
